# -*- coding: utf-8 -*-
# @Time : 2025/7/16 23:57
# @Author : Lpb
# @File : TestCaseV1CheckCreateTask.py
import unittest
import time
from business.voices.vo import BusinessRe
from common.assertCommon import AssertCommon
from common.yamlLoader import YamlRead
from utils.utils_file import load_json_from_project


class TestInspectTask(unittest.TestCase):
    def setUp(self):
        self.ac = AssertCommon()
        self.env_config = YamlRead().env_config1()
        self.host = self.env_config['host']
        self.authorization = self.env_config['Authorization']
        self.br = BusinessRe()
        self.task_files = [
            "data/response/task/v1/create_task_audio&video_v1.json",
            "data/response/task/v1/create_task_onlyAudio_8_v1.json",
            "data/response/task/v1/create_task_onlyAudio_20_v1.json",
            "data/response/task/v1/create_task_tts_8.json",
            "data/response/task/v1/create_task_tts_20.json"
        ]

    def test_check_task_status(self):
        for relative_path in self.task_files:
            try:
                data = load_json_from_project(relative_path)
            except FileNotFoundError as e:
                print(f"[WARN] 跳过，文件未找到：{e}")
                continue

            job_id = data.get("job_id")
            if not job_id:
                print(f"[WARN] {relative_path} 中未找到 job_id")
                continue

            print(f"开始轮询 job_id: {job_id}，来自文件: {relative_path}")
            self.poll_task_status(job_id)

    def poll_task_status(self, job_id, max_retries=30, interval=60):
        url = self.host + '/api/v1/hifly/task/inspect'
        body = {
            "job_id": job_id
        }

        last_status = None
        repeat_count = 0

        for i in range(max_retries):
            res = self.br.post(url, self.authorization, body)
            if res.status_code != 200:
                print(f"[ERROR] 请求失败 status_code={res.status_code}，response={res.text}")
                break

            res_json = res.json()
            status = res_json.get("status")

            print(f"[轮询第{i+1}次] job_id: {job_id}，status: {status}（1=等待中, 2=处理中, 3=完成, 4=失败）")

            if status in (3, 4):
                print(f"✅ 任务已完成或失败，status={status}，停止轮询")
                break

            # 检测是否一直卡在某个状态
            if status == last_status:
                repeat_count += 1
            else:
                repeat_count = 0
                last_status = status

            if repeat_count >= 10:
                print(f"[WARN] 状态 {status} 连续 {repeat_count} 次未变化，可能已卡住，强制退出")
                break

            time.sleep(interval)
        else:
            self.fail(f"❌ 任务 {job_id} 在最大轮询次数 {max_retries} 内未完成")

if __name__ == '__main__':
    unittest.main()






